package sun.net.www.protocol.classpath;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;

/**
 * @description: Handler
 * @author: general
 * @version: 1.0
 * @create: 2021-10-27 22:01
 **/
public class Handler extends URLStreamHandler {

    @Override
    protected URLConnection openConnection(URL resource) throws IOException {
        return new ClassPathURLConnection(resource);
    }
}

class ClassPathURLConnection extends URLConnection {

    /**
     * Constructs a URL connection to the specified URL. A connection to
     * the object referenced by the URL is not created.
     *
     * @param resource the specified URL.
     */
    protected ClassPathURLConnection(URL resource) {
        super(resource);
    }

    @Override
    public void connect() throws IOException {
    }

    public InputStream getInputStream() throws IOException {
        URL resource = getURL();
        String resourcePath = resource.getPath();
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        while (resourcePath.startsWith("/")) {
            resourcePath = resourcePath.substring(1);
        }
        return classLoader.getResourceAsStream(resourcePath);
    }
}